package reduce.fz.com.reduce.util;

import android.content.res.Configuration;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SeekBar;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import reduce.fz.com.reduce.util.base.ReduceApplication;

public class VideoPlayerUtils implements OnBufferingUpdateListener,
        OnCompletionListener, OnPreparedListener, SurfaceHolder.Callback,
        OnErrorListener, MediaPlayer.OnInfoListener {

    private int videoWidth;
    private int videoHeight;
    public MediaPlayer mediaPlayer;
    private SurfaceHolder surfaceHolder;
    private Timer mTimer = new Timer();

    private onPlayTimeChangeListener onPlayTimeChangeListener;
    private onPlayCompletionListener onPlayCompletionListener;
    private onPlayerErrorListener onPlayerErrorListener;
    private int positionProgress;
    private boolean isseekTo;
    private int position;
    private String videoUrl;
    public boolean isPlaying;

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        if (what == mp.MEDIA_INFO_BUFFERING_START) {
            mediaPlayer.pause();
            //progressBar.setVisibility(View.VISIBLE);
            return true;
        } else if (what == mp.MEDIA_INFO_BUFFERING_END) {
            mediaPlayer.start();
            //progressBar.setVisibility(View.GONE);
            return true;
        }
        return false;
    }


    public enum PlayState {
        START, FINISH,
    }

    public enum ErrorType {
        UNKNOWN, OTHER,
    }

    public void setonPlayTimeChangeListener(
            onPlayTimeChangeListener onPlayTimeChangeListener) {
        this.onPlayTimeChangeListener = onPlayTimeChangeListener;

    }

    public void setonPlayCompletionListener(
            onPlayCompletionListener onPlayCompletionListener) {
        this.onPlayCompletionListener = onPlayCompletionListener;

    }

    public void setonPlayerErrorListener(
            onPlayerErrorListener onPlayerErrorListener) {
        this.onPlayerErrorListener = onPlayerErrorListener;

    }

    public VideoPlayerUtils(SurfaceView surfaceView) {
      //  this.skbProgress = skbProgress;
        //this.progressBar = progressBar;
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        mTimer.schedule(mTimerTask, 0, 1000);

    }

    TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            try {
                if (null == mediaPlayer) return;
                /*if (skbProgress.isPressed() == false) {
                    handleProgress.sendEmptyMessage(0);
                }*/
            } catch (Throwable e) {
                ReduceLog.e(e);
            }
        }
    };

    Handler handleProgress = new Handler() {
        public void handleMessage(Message msg) {
            try {
                if (null == mediaPlayer)
                    return;
                positionProgress = mediaPlayer.getCurrentPosition();
                int duration = mediaPlayer.getDuration();
                onPlayTimeChangeListener.onTimeChange(positionProgress);

               /* if (duration > 0) {
                    long pos = skbProgress.getMax() * positionProgress / duration;
                    skbProgress.setProgress((int) pos);
                }*/
            } catch (Throwable e) {
                ReduceLog.e(e);
            }
        }
    };

    public void play() {
        mediaPlayer.start();
    }

    public void playUrl(String videoUrl) {
        try {
            startVideo(videoUrl);
            this.videoUrl = videoUrl;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        if (mediaPlayer != null)
            mediaPlayer.pause();
    }

    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }




    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDisplay(surfaceHolder);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
            mediaPlayer.setOnErrorListener(this);
            mediaPlayer.setOnInfoListener(this);
        } catch (Exception e) {
            ReduceLog.e(e);
        }
    }

    private void startVideo(String videoUrl) throws IOException {
        this.videoUrl = videoUrl;
        try {
            if (null == mediaPlayer)
                mediaPlayer = new MediaPlayer();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.prepareAsync();
            mediaPlayer.setDisplay(surfaceHolder);
            mediaPlayer.start();

        } catch (Exception e) {
            ReduceLog.e(e);
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        if (position != 0) {
            try {
               /* if (progressBar.getVisibility() != View.VISIBLE) {
                    progressBar.setVisibility(View.VISIBLE);
                }*/
                startVideo(videoUrl);
                if (!isPlaying)
                    mediaPlayer.pause();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            isPlaying = mediaPlayer.isPlaying();
            position = mediaPlayer.getCurrentPosition();
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;

        }

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        videoWidth = mediaPlayer.getVideoWidth();
        videoHeight = mediaPlayer.getVideoHeight();
        if (videoHeight != 0 && videoWidth != 0) {
            mp.start();
            handleProgress.postDelayed(new Runnable() {
                @Override
                public void run() {
                   // progressBar.setVisibility(View.GONE);
                    if(onPlayCompletionListener!=null) {
                        onPlayCompletionListener.PlayCompletion(PlayState.START);
                    }
                }
            }, 800);
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if(onPlayCompletionListener!=null)
        onPlayCompletionListener.PlayCompletion(PlayState.FINISH);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
      //  skbProgress.setSecondaryProgress(percent);

        if (positionProgress != 0 && isseekTo) {
            mediaPlayer.seekTo(positionProgress + 100);
            isseekTo = false;
        }
    }

    public interface onPlayTimeChangeListener {
        void onTimeChange(int time);
    }

    public interface onPlayCompletionListener {
        void PlayCompletion(PlayState playstate);
    }

    public interface onPlayerErrorListener {
        void onPlayerErrorListener(ErrorType errortype);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {

        switch (what) {
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                break;
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                break;
            case MediaPlayer.MEDIA_ERROR_IO:
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                try {
                    String newUrl = videoUrl.replace("http://v.feelapp.cc", "http://112.126.69.135:8080");
                    startVideo(newUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
        return true;
    }

}
